import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import '../services/database_service.dart';

class ImportExportScreen extends StatefulWidget {
  const ImportExportScreen({super.key});

  @override
  _ImportExportScreenState createState() => _ImportExportScreenState();
}

class _ImportExportScreenState extends State<ImportExportScreen> {
  final DatabaseService _databaseService = DatabaseService();

  Future<void> _exportWords(BuildContext context) async {
    try {
      // 获取需要导出的单词数据
      final words = await _databaseService.exportWords();
      final jsonData = jsonEncode(words);

      // 获取iOS的文档目录
      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/words_backup_${DateTime.now().millisecondsSinceEpoch}.json');

      // 写入文件
      await file.writeAsString(jsonData);

      // 提示用户导出成功，并提供打开文件的选项
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('导出成功：${file.path}'),
          action: SnackBarAction(
            label: '打开',
            onPressed: () async {
              // 使用 open_file 插件尝试打开文件
              OpenResult result = await OpenFile.open(file.path);
              switch (result.type) {
                case ResultType.fileNotFound:
                  print("文件未找到");
                  break;
                case ResultType.permissionDenied:
                  print("权限被拒绝");
                  break;
                case ResultType.noAppToOpen:
                  print("没有应用可以打开该文件");
                  break;
                default:
                  print("文件已成功打开");
              }
            },
          ),
        ),
      );
    } catch (e) {
      // 如果发生错误，通知用户
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('导出失败：$e')),
      );
    }
  }

  Future<void> _importWords() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['json'],
      );

      if (result != null) {
        final file = File(result.files.single.path!);
        final jsonData = await file.readAsString();
        final List<dynamic> words = jsonDecode(jsonData);

        await _databaseService.importWords(
          words.map((w) => Map<String, dynamic>.from(w)).toList(),
        );

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导入成功：${words.length}个单词')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('导入失败：$e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('导入导出'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            ElevatedButton.icon(
              icon: const Icon(Icons.file_upload),
              label: const Text('导出单词数据'),
              onPressed: () async {
                _exportWords(context);
              },
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              icon: const Icon(Icons.file_download),
              label: const Text('导入单词数据'),
              onPressed: _importWords,
            ),
            const SizedBox(height: 32),
            Text(
              '说明：\n'
              '1. 导出的文件将保存在应用文档目录下\n'
              '2. 导入时请选择之前导出的JSON文件\n'
              '3. 导入将不会删除现有单词，只会添加新单词',
              style: TextStyle(color: Colors.grey[600]),
            ),
          ],
        ),
      ),
    );
  }
}
